//
//  CreatClassViewController.m
//  BOSS-SOOC
//
//  Created by apple on 16/8/29.
//  Copyright © 2016年 Gcx. All rights reserved.
//
#define _vc_start_postion 0
#define REDCOLOR [self getColor:@"e86666"]
#define normalColor [UIColor colorWithRed:26.0/255 green:151.0/255 blue:233.0/255 alpha:1.0f]
#define SCALE0000 0.383
#define Colorf5f5f5 [UIColor colorWithRed:245.0/255 green:245.0/255 blue:245.0/255 alpha:1.0f]


#import "CreatClassViewController.h"
#import "SCTypeBtn.h"
#import "SC_TextFeild.h"
#import "MyClassModel.h"
#import "SC_PopView.h"

@interface CreatClassViewController()<UITextFieldDelegate,UIPickerViewDelegate,UIPickerViewDataSource>{

    SCTypeBtn   *_succeedBtn;
    NSArray     *_textArr;
    NSArray     *_textFeildArr;
    UISwitch    *_noOrLYes;
    UIButton    *_addBtn;
    UIView      *_mainView;
    
    NSArray     *_feildArr;//承载textField的数组
}

@property (nonatomic, strong) NSMutableArray *myClassArr;

@property (nonatomic, strong) UIPickerView *picker;

@property (nonatomic, strong) NSString *nameString;

@property (strong, nonatomic)  SC_TextFeild *nameT;
@property (strong, nonatomic)  SC_TextFeild *zhutiT;
@property (strong, nonatomic)  SC_TextFeild *dizhiT;
@property (strong, nonatomic)  SC_TextFeild *timeT;
@property (strong, nonatomic)  SC_TextFeild *xueqiT;
@end


@implementation CreatClassViewController

- (void)viewDidLoad{
    
    [super viewDidLoad];
    
    [self setNavBarTitle:@"创建课堂"];
    
    [self buildUI];
    
    [self classInfomation];
}

/*
 签到-教师创建课堂时获取课堂信息
 mod=Sign&act=getClass
 
 Data内容	Data中数组每个元素的组成
 参数名称	类型	描述
 sckcm		上次课程名
 scktzt		上次课堂主题
 scskdd		上次上课地点
 skrq		上课日期
 skxq		上课学期
 myclasses	子json	返回该教师创建过的课程，数组以中括号返回，json以大括号返回  如果数据为空，返回空数组，切记
 
 myclasses内容	myclasses中数组每个元素的组成
 参数名称	类型	描述
 kcmc		课堂名称
 */
#pragma mark -- 创建课堂时获取课堂信息
- (void)classInfomation{

    NSDictionary *dic = @{@"oauth_token":@"815bffb68e2ea44e38cf16a98a5a29a4",@"oauth_token_secret":@"8e84bc64f03d73b5c75406ef1d7349f7"};
    
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithDictionary:dic];
    
    SCHttpRequest *request = [[SCHttpRequest alloc]initWithApi:API_getClass
                                                        params:params];
    [self doPOSTConnect:request start:^(SCHttpRequest * _Nonnull req) {
        
    } success:^(SCHttpRequest * _Nonnull req, SCHttpResponse * _Nonnull resp) {
                
        if ([resp.originalDictionary[@"status"] integerValue] == 0) {
            
            NSDictionary *dic = resp.originalDictionary[@"data"];
            
            _timeT.text = [NSString stringWithFormat:@"%@", dic[@"skrq"]];
            _nameT.text = [NSString stringWithFormat:@"%@", dic[@"sckcm"]];
            _xueqiT.text = [NSString stringWithFormat:@"%@",dic[@"skxq"]];
            
            NSArray *arr = dic[@"myclasses"];
            
            for (NSDictionary *dic in arr) {
                
                MyClassModel *model = [MyClassModel modelWithDic:dic];
                
                [self.myClassArr addObject:model.kcmc];
            }
            
            
            if(self.myClassArr.count == 0){
#pragma mark - -------pick是空  隐藏按钮
                
                _addBtn.hidden = YES;
                
            }else{
                
                _addBtn.hidden = NO;
            }

        } else {
        
            POST_FAIL(resp.originalDictionary[@"statusCode"]);
        }
        
    } failure:^(SCHttpRequest * _Nonnull req, NSError * _Nonnull error) {
        
    } finish:^(SCHttpRequest * _Nonnull req, BOOL success) {
        
    }];

}

- (void)creatPickerView{

    _mainView = [[UIView alloc]initWithFrame:CGRectMake(16, SIZEHEIGHT/2 - 182, SIZEWIDTH - 32, 364)];
    
    _mainView.backgroundColor = [UIColor whiteColor];
    
    _mainView.alpha = 1;
    
    _mainView.layer.masksToBounds = YES;
    
    _mainView.layer.cornerRadius = 5;
    
    UILabel *topLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, SIZEWIDTH - 32, 49)];
    
    topLabel.backgroundColor = Colorf5f5f5;
    
    topLabel.text = @"请选择课程名称";
    
    topLabel.textAlignment = NSTextAlignmentCenter;
    
    topLabel.textColor = Color333333;
    
    topLabel.font = NormalFont(42);
    
    [_mainView addSubview:topLabel];
    
    UIButton *succeedBtn = [self buttonWithFrame:CGRectMake(SIZEWIDTH - 98, 314 , 56, 40) type:UIButtonTypeCustom title:@"确定"];
    [succeedBtn addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];

    [_mainView addSubview:succeedBtn];
    
    _picker = [[UIPickerView alloc]initWithFrame:CGRectMake(ScaleSize(42), CGRectGetMaxY(topLabel.frame), SIZEWIDTH - 32 - ScaleSize(84), 259)];
    
    _picker.delegate = self;
    
    _picker.dataSource = self;
    
    _nameString = self.myClassArr[0];
    
    [_mainView addSubview:_picker];
}


- (UIButton *)buttonWithFrame:(CGRect)frame type:(UIButtonType)type title:(NSString *)title{
    
    
    UIButton *button = [UIButton buttonWithType:type];
    
    button.layer.masksToBounds = YES;
    
    button.layer.borderWidth = 0.5;
    [button setTitleColor:normalColor forState:UIControlStateNormal];
    
    [button setBackgroundImage:[self imageWithColor:[UIColor whiteColor]] forState:UIControlStateNormal];
    
    [button setBackgroundImage:[self imageWithColor:BGC] forState:UIControlStateHighlighted];
    
    button.titleLabel.font = NormalFont(42);
    
    button.layer.borderColor = [UIColor clearColor].CGColor;
    
    
    button.frame = frame;
    
    [button setTitle:title forState:UIControlStateNormal];
    
    return button;
    
}

-(void)buttonClicked:(UIButton *)sender{

    self.nameT.text = _nameString;
    
    [self closeAndBack];
    
}

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view{
    UILabel* pickerLabel = (UILabel*)view;
    if (!pickerLabel){
        pickerLabel = [[UILabel alloc] init];
        [pickerLabel setTextAlignment:NSTextAlignmentCenter];
        [pickerLabel setBackgroundColor:[UIColor clearColor]];
        [pickerLabel setFont:NormalFont(42)];
        pickerLabel.textColor = Color333333;
    }
    // Fill the label text here
    pickerLabel.text=[self pickerView:pickerView titleForRow:row forComponent:component];
    return pickerLabel;
}

- (void)disMissMainView{
    
    [_mainView removeFromSuperview];
    
}

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    
    return 1;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    
    return _myClassArr.count;
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    
    _nameString = self.myClassArr[row];
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    
    return [self.myClassArr objectAtIndex:row];
}

/**
 
 *用color生成图片
 
 
 */

- (UIImage *)imageWithColor:(UIColor *)color {
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return image;
}


/**
 *  界面
 */
- (void)buildUI{

    
    _textArr = @[@"课程名称: ",@"课堂主题: ",@"上课地点: ",@"上课时间: ",@"上课学期: ",@"拍照签到: "];
    
    _textFeildArr = @[@"请输入课程",@"请输入课堂主题",@"选填",@"",@"选填"];
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    UIScrollView *bigScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 64, SIZEWIDTH, SIZEHEIGHT)];
    bigScrollView.contentSize = CGSizeMake(0, 480+50);
    bigScrollView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:bigScrollView];
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, _vc_start_postion, SIZEWIDTH, 360)];
    view.backgroundColor = [UIColor whiteColor];
    [bigScrollView addSubview:view];
    
    for (int i = 1; i <= 6; i++) {
        
        UIView *xianView = [[UIView alloc]initWithFrame:CGRectMake(ScaleSize(42), i*60, SIZEWIDTH-ScaleSize(84), 0.5)];
        xianView.backgroundColor = colordbdbdb;
        [view addSubview:xianView];
        
    }
    
    for (int i = 0; i < 2; i++) {
        UILabel *star=[[UILabel alloc]initWithFrame:CGRectMake(ScaleSize(33), 23+i*60, 10, 20)];
        star.text=@"*";
        star.textColor = REDCOLOR;
        [view addSubview:star];
        
    }
    
    _succeedBtn = [[SCTypeBtn alloc]initWithFrame:CGRectMake(ScaleSize(60), CGRectGetMaxY(view.frame)+ScaleSize(96), SIZEWIDTH - ScaleSize(120), ScaleSize(140))];
    [_succeedBtn setTitle:@"提交" forState:UIControlStateNormal];
    [_succeedBtn addTarget:self action:@selector(succeedBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
    [bigScrollView addSubview:_succeedBtn];
    _succeedBtn.isCanUse = NO;

    for (int i = 0; i < 6; i++) {
        UILabel *label = [self labelWithFrame:CGRectMake(ScaleSize(33), 20+i*60, 75, 20) andText:_textArr[i]];
        [view addSubview:label];
        
        if (i == 0 || i == 1) {
            
            label.frame = CGRectMake(ScaleSize(33)+10, 20+i*60, 75, 20);
        }
        
    }
    
    for (int i = 0; i < 5; i++) {
        SC_TextFeild *textFeild = [[SC_TextFeild alloc]initWithFrame:CGRectMake(80, 20+i*60, SIZEWIDTH - 100 - ScaleSize(33), 20)];
        textFeild.tag = 1000+i;
        textFeild.delegate = self;
        textFeild.font = NormalFont(42);
        textFeild.textColor = Color333333;
        textFeild.placeholder = _textFeildArr[i];
        [textFeild setValue:colordbdbdb forKeyPath:@"_placeholderLabel.textColor"];
        [textFeild setValue:NormalFont(42) forKeyPath:@"_placeholderLabel.font"];
        textFeild.clearButtonMode = UITextFieldViewModeWhileEditing;

        if (textFeild.tag != 1000) {
            
            textFeild.frame = CGRectMake(80, 20+i*60, SIZEWIDTH - 80 - ScaleSize(33), 20);
        }
        
        if (textFeild.tag == 1000 ) {
            
            textFeild.frame = CGRectMake(90, 20+i*60, SIZEWIDTH - 110 - ScaleSize(33), 20);
        }
        
        if (textFeild.tag == 1001) {
            
            textFeild.frame = CGRectMake(90, 20+i*60, SIZEWIDTH - 90 - ScaleSize(33), 20);
            
        }
        
        [view addSubview:textFeild];
        
    }
    
    _nameT  = (SC_TextFeild *)[self.view viewWithTag:1000];
    _zhutiT = (SC_TextFeild *)[self.view viewWithTag:1001];
    _dizhiT = (SC_TextFeild *)[self.view viewWithTag:1002];
    _timeT  = (SC_TextFeild *)[self.view viewWithTag:1003];
    _xueqiT = (SC_TextFeild *)[self.view viewWithTag:1004];
    
    _feildArr = @[_nameT,_zhutiT];
    
    _nameT.myBlock = ^(NSString *str){

        if (_nameT.text.length > 0 && _zhutiT.text.length > 0) {
            
            _succeedBtn.isCanUse = YES;
        } else {
            _succeedBtn.isCanUse = NO;

        }
    };
    
    _zhutiT.myBlock = ^(NSString *str){
        
        if (_nameT.text.length > 0 && _zhutiT.text.length > 0) {
            
            _succeedBtn.isCanUse = YES;
        } else {
            _succeedBtn.isCanUse = NO;
            
        }
    };
    
    
    
    _noOrLYes = [[UISwitch alloc]initWithFrame:CGRectMake(-ScaleSize(54)+SIZEWIDTH - 55, 60*5+20, 0, 0)];
    [view addSubview:_noOrLYes];
    
    _noOrLYes.on = NO;
    _noOrLYes.onTintColor = normalColor;

    _addBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    
    [_addBtn setImage:[UIImage imageNamed:@"创建课堂-选择课程"] forState:UIControlStateNormal];
    _addBtn.frame =CGRectMake(SIZEWIDTH - 20- ScaleSize(33), 20, 20, 20);

    [_addBtn addTarget:self action:@selector(popViewShow) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:_addBtn];
}

- (void)succeedBtnClicked:(UIButton *)sender{

    NSArray *array = [_nameT.text componentsSeparatedByString:@" "]; //从字符A中分隔成2个元素的数组
    
    NSLog(@"array == %ld", array.count);
    
    NSArray *array1 = [_zhutiT.text componentsSeparatedByString:@" "]; //从字符A中分隔成2个元素的数组
    
    NSLog(@"array == %ld", array1.count);
    
    if (array.count == _nameT.text.length+1|| array1.count == _zhutiT.text.length+1) {
        
        [[JLActionManager sharedInstance]showHUDWithLabelText:@"课程名称或主题不能为空" imageView:FailImage inView:self.view];
    } else if (_dizhiT.text.length > 50){
        
        [[JLActionManager sharedInstance]showHUDWithLabelText:@"上课地点不得超过50位" imageView:FailImage inView:self.view];
        
        
    }else {
        
        if (_nameT.text.length > 50 || _zhutiT.text.length > 50) {
            [[JLActionManager sharedInstance]showHUDWithLabelText:@"课程名称或主题不得超过50位" imageView:FailImage inView:self.view];
        } else {
            
            BOOL isHave = false;
            
            for (int i = 0; i < self.myClassArr.count; i++) {
                
                if ([_nameT.text isEqualToString:self.myClassArr[i]]) {
                    
                    NSLog(@"%d", i);
                    /**
                     *  已存在
                     */
                    isHave = true;
                    
                } else {
                
                    /**
                     *  不存在
                     */
                    isHave = false;
                    
                    
                }
                
            }
            
            if (isHave == true) {
                
                [self creatClass:_noOrLYes.on];

            } else {
            
                [self creatCourse];

            }
            
        }
    }


}

/**
 *  创建课堂
 */
- (void)creatClass:(BOOL)isHave{
    
    NSDictionary *dic = @{@"oauth_token":@"815bffb68e2ea44e38cf16a98a5a29a4",@"oauth_token_secret":@"8e84bc64f03d73b5c75406ef1d7349f7"};
    
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithDictionary:dic];
    [params setObject:_nameT.text forKey:@"kcmc"];
    [params setObject:_zhutiT.text forKey:@"ktzt"];
    [params setObject:_dizhiT.text forKey:@"skdd"];
    
    if (isHave == YES) {
        
        [params setObject:@1 forKey:@"pzqd"];
    } else {
    
        [params setObject:@0 forKey:@"pzqd"];

    }
    
    SCHttpRequest *request = [[SCHttpRequest alloc]initWithApi:API_createClass
                                                        params:params];
    [self doPOSTConnect:request start:^(SCHttpRequest * _Nonnull req) {
        
    } success:^(SCHttpRequest * _Nonnull req, SCHttpResponse * _Nonnull resp) {
        
        NSLog(@"resp == %@", resp.originalDictionary);
        
        if ([resp.originalDictionary[@"status"] integerValue] == 0) {
            
            POST_SUCCEED(resp.originalDictionary[@"statusCode"]);
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                [self.navigationController popViewControllerAnimated:YES];
                
            });

            
        } else {
            
            POST_FAIL(resp.originalDictionary[@"statusCode"]);
        }
        
    } failure:^(SCHttpRequest * _Nonnull req, NSError * _Nonnull error) {
        
    } finish:^(SCHttpRequest * _Nonnull req, BOOL success) {
        
    }];

}

/**
 *  创建课程
 */
- (void)creatCourse{
    
    NSDictionary *dic = @{@"oauth_token":@"815bffb68e2ea44e38cf16a98a5a29a4",@"oauth_token_secret":@"8e84bc64f03d73b5c75406ef1d7349f7"};
    
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithDictionary:dic];
    [params setObject:_nameT.text forKey:@"kcmc"];

    
    SCHttpRequest *request = [[SCHttpRequest alloc]initWithApi:API_createCourse
                                                        params:params];
    [self doPOSTConnect:request start:^(SCHttpRequest * _Nonnull req) {
        
    } success:^(SCHttpRequest * _Nonnull req, SCHttpResponse * _Nonnull resp) {
        
        NSLog(@"resp == %@", resp.originalDictionary);
        
        if ([resp.originalDictionary[@"status"] integerValue] == 0) {
            
            [self creatClass:_noOrLYes.on];
            
//            POST_SUCCEED(resp.originalDictionary[@"statusCode"]);

            
        } else {
            
            POST_FAIL(resp.originalDictionary[@"statusCode"]);
        }
        
    } failure:^(SCHttpRequest * _Nonnull req, NSError * _Nonnull error) {
        
    } finish:^(SCHttpRequest * _Nonnull req, BOOL success) {
        
    }];
    
}


- (void)popViewShow {

    
    [self creatPickerView];
    //    看看pop效果把下面这一句加上
    
    [SC_PopView sharedInstance].shadeBackgroundType = ShadeBackgroundTypeSolid;
    [SC_PopView sharedInstance].closeButtonType = ButtonPositionTypeRight;
    [[SC_PopView sharedInstance] showWithPresentView:_mainView animated:YES];
    
}

- (void)closeAndBack {
    [[SC_PopView sharedInstance] closeWithBlcok:^{
//        [self.navigationController popViewControllerAnimated:YES];
    }];
}
-(UIColor *)getColor:(NSString *)hexColor {
    unsigned int red,green,blue;
    NSRange range;
    range.length = 2;
    
    range.location = 0;
    [[NSScanner scannerWithString:[hexColor substringWithRange:range]] scanHexInt:&red];
    
    range.location = 2;
    [[NSScanner scannerWithString:[hexColor substringWithRange:range]] scanHexInt:&green];
    
    range.location = 4;
    [[NSScanner scannerWithString:[hexColor substringWithRange:range]] scanHexInt:&blue];
    
    return [UIColor colorWithRed:(float)(red/255.0f) green:(float)(green / 255.0f) blue:(float)(blue / 255.0f) alpha:1.0f];
}

- (UILabel *)labelWithFrame:(CGRect)frame andText:(NSString *)text {
    
    UILabel *label = [[UILabel alloc] init];
    
    label.frame = frame;
    
    label.font = NormalFont(42);
    
    label.text = text;
    
    label.textColor = Color333333;
    
    return label;
    
}

- (NSMutableArray *)myClassArr{

    if (!_myClassArr) {
        _myClassArr = [NSMutableArray array];
    }
    return _myClassArr;
}

@end
